#include <iostream>
#include <pthread.h>
#include <queue>
#include <vector>
#include "Thread.hpp"

using namespace std;
using namespace ThreadModule;
const static int gthreadnums = 4;

template <typename T>
class ThreadPool
{
private:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void UnLock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void WakeUp()
    {
        pthread_cond_signal(&_cond);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    void ALLWakeUp()
    {
        pthread_cond_broadcast(&_cond);
    }

public:
    ThreadPool(int threadnum = gthreadnums) : _threadnum(threadnum), _waitnum(0), _isrunning(false)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
        Log(INFO, "ThreadPool Construct....");
    }
    ThreadPool<T> operator&=(const ThreadPool<T> &) = delete;
    ThreadPool(const ThreadPool<T> &) = delete;

    static ThreadPool<T> *Getinstance()
    {
        // 只有第一次会创建对象，后续都是获取
        // 双判断的方式，可以有效减少获取单例的加锁成本，而且保证线程安全
        if (nullptr == _instance) // 保证第二次之后，所有线程，不用在加锁，直接返回_instance单例对象
        {
            LockGuard lockguard(&_lock);
            if (nullptr == _instance)
            {
                _instance = new ThreadPool<T>();
                _instance->InitThreadpool();
                _instance->Start();
                Log(DEBUG, "创建线程池单例");
                return _instance;
            }
        }
        Log(DEBUG, "获取线程池单例");
        return _instance;
    }

    // 报错invalid use of non-static member function ‘void ThreadPool<T>::Print() [with T = int]
    // 因为内部有this指针，而函数类型是void()
    // 前面+static或者用bind
    // 回调的是其他类的成员函数

    void HanderTask(string name)
    {
        Log(INFO, "%s is running...", name.c_str());

        while (1)
        {
            // 上锁
            Lock();
            while (_task_queue.empty() && _isrunning)
            {
                // 没有任务就等待
                _waitnum++;
                ThreadSleep();
                _waitnum--;
            }
            // 2.1 如果线程池已经退出了 && 任务队列是空的
            if (_task_queue.empty() && !_isrunning)
            {
                UnLock();
                break;
            }
            // 获取任务
            T t = _task_queue.front();
            _task_queue.pop();
            Log(DEBUG, "%s gets task %s", name.c_str(), t.DebugToString().c_str());
            // 解锁
            UnLock();
            // 处理任务
            t();
            Log(DEBUG, "%s get testresult: %s", name.c_str(), t.ResultToString().c_str());
        }
    }
    // 初始化
    void InitThreadpool()
    {
        for (int num = 0; num < _threadnum; num++)
        {
            string name = "thread-" + to_string(num + 1);
            // _threads.emplace_back(Print, name);
            _threads.emplace_back(bind(&ThreadPool::HanderTask, this, placeholders::_1), name);
            Log(INFO, "init thread %s done", name.c_str());
        }
        _isrunning = true; // 不在这里，有些线程会直接进入，判断Is_running是fasle
    }
    // 启动
    void Start()
    {
        for (auto &thread : _threads)
        {
            thread.Start();
        }
    }
    void Stop()
    {
        Lock();
        _isrunning = false;
        ALLWakeUp();
        UnLock();
    }
    void Wait()
    {
        for (auto &thread : _threads)
        {
            thread.Join();
            Log(INFO, "%s is quit...", thread.name().c_str());
        }
    }
    bool Enqueue(const T &in)
    {
        bool ret = false;
        Lock();
        if (_isrunning)
        {
            _task_queue.push(in);
            if (_waitnum > 0)
            {
                WakeUp(); // 等待多了就需要唤醒
            }
            ret = true;
        }
        UnLock();
        return ret;
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    int _threadnum;
    int _waitnum;
    vector<Thread> _threads;
    queue<T> _task_queue; // 任务队列
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
    bool _isrunning;
    // 单例模式
    static ThreadPool<T> *_instance;
    static pthread_mutex_t _lock;
};
template <typename T>
ThreadPool<T> *ThreadPool<T>::_instance = nullptr;
template <typename T>
pthread_mutex_t ThreadPool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;